package com.unknown.wificontrol.ui.images;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.unknown.wificontrol.MainActivity;
import com.unknown.wificontrol.R;
import com.unknown.wificontrol.http.Http;
import com.unknown.wificontrol.http.HttpListener;
import com.unknown.wificontrol.ui.BaseFragment;
import com.unknown.wificontrol.util.Util;

import org.json.JSONObject;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class DashboardFragment extends BaseFragment {

    @Override
    public int getLayout() {
        return R.layout.fragment_images;
    }

    private Handler handler = new Handler();

    @BindView(R.id.ivPhoto)
    ImageView ivPhoto;

    private boolean isStarting = false;


    private String currentUrl = "";

    @Override
    public void initViews(View parent) {

    }


    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            getPhoto();
            if (isStarting) {
                handler.postDelayed(runnable, 1000);
            }
        }
    };

    private synchronized void getPhoto() {
        Http.get(getDomain() + "/getPhoto", "", new HttpListener() {
            @Override
            public void onReturn(JSONObject jsonObject) {
                if (jsonObject != null && jsonObject.length() > 0) {
                    int code = jsonObject.optInt("code");
                    if (code == 200) {
                        currentUrl = jsonObject.optString("message");
                        Log.e("tag", "=====再次采集图片===" + currentUrl);
                        Picasso.with(mActivity).load(currentUrl).into(ivPhoto);
                    }
                }
            }
        });
    }

    @BindView(R.id.btnShot)
    Button btnShot;

    @OnClick(R.id.btnShot)
    void onShot() {
        isStarting = !isStarting;
        btnShot.setText(isStarting ? "停止采集" : "图形采集");
        if (isStarting) {
            handler.post(runnable);
        } else {
            handler.removeCallbacks(runnable);
        }
    }

    @OnClick(R.id.btnHistory)
    void onHistory() {
        changeView(HistoryActivity.class);
    }

    @OnClick(R.id.btnSaveImg)
    void onSaveImage() {
        XXPermissions.with(mActivity)
                // 申请单个权限
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        if (all) {
                            saveImg();
                        } else {
                            showToast("获取存储权限失败");
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean never) {
                        if (never) {
                            showToast("被永久拒绝授权，请手动授予存储权限");
                            XXPermissions.startPermissionActivity(mActivity, denied);
                        } else {
                            showToast("获取存储权限失败");
                        }
                    }
                });


    }

    private void saveImg() {
        if (TextUtils.isEmpty(currentUrl)) {
            showToast("未采集到图片");
            return;
        }
        if (isStarting) {
            isStarting = false;
            handler.removeCallbacks(runnable);
            save(true);
        } else {
            save(false);
        }
    }

    private void save(boolean isRestart) {
        showProgress("保存中...");
        Target target = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final File file = Util.saveFiles(mActivity, bitmap);
                        hideProgress();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (file != null) {
                                    showToast("保存成功");
                                } else {
                                    showToast("保存失败");
                                }
                                if (isRestart) {
                                    //重启采集
                                    isStarting = true;
                                    handler.post(runnable);
                                }
                            }
                        });
                    }
                }).start();
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                showToast("保存失败");
                if (isRestart) {
                    //重启采集
                    isStarting = true;
                    handler.post(runnable);
                }
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        };
        Picasso.with(mActivity).load(currentUrl).into(target);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isStarting) {
            handler.removeCallbacks(runnable);
            handler.post(runnable);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (isStarting) {
            handler.removeCallbacks(runnable);
        }
    }
}